package com.xhy.documents_collection.service.team.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xhy.documents_collection.enums.ServiceType;
import com.xhy.documents_collection.holder.UserHolder;
import com.xhy.documents_collection.entity.PO.log.SysLog;
import com.xhy.documents_collection.entity.PO.User;
import com.xhy.documents_collection.entity.PO.task.Task;
import com.xhy.documents_collection.entity.PO.task.TaskRecord;
import com.xhy.documents_collection.entity.PO.task.TaskUser;
import com.xhy.documents_collection.entity.PO.team.Team;
import com.xhy.documents_collection.entity.PO.team.TeamUser;
import com.xhy.documents_collection.entity.PO.team.UserRole;
import com.xhy.documents_collection.mapper.team.TeamMapper;
import com.xhy.documents_collection.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhy.documents_collection.service.async.AsyncService;
import com.xhy.documents_collection.service.authority.UserRoleService;
import com.xhy.documents_collection.service.oss.OssService;
import com.xhy.documents_collection.service.task.TaskRecordService;
import com.xhy.documents_collection.service.task.TaskService;
import com.xhy.documents_collection.service.task.TaskUserService;
import com.xhy.documents_collection.service.team.TeamService;
import com.xhy.documents_collection.service.team.TeamUserService;
import com.xhy.documents_collection.utils.R;
import com.xhy.documents_collection.utils.UuidUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xhy
 * @since 2022-11-14
 */
@Service
@Slf4j
public class TeamServiceImpl extends ServiceImpl<TeamMapper, Team> implements TeamService {

    @Resource
    private TaskService taskService;

    @Resource
    private TaskRecordService taskRecordService;

    @Resource
    private TeamUserService teamUserService;

    @Resource
    private TaskUserService taskUserService;


    @Resource
    private AsyncService asyncService;
    @Override
    @Transactional
    public R removeTeams(String ids) {
        try {
            // 获取团队ids
            List<String> teamIds = Arrays.asList(ids.split(","));
            // 删除团队
            baseMapper.deleteBatchIds(teamIds);
            // 查出团队下的所有任务
            List<Integer> taskIds = taskService.list(new QueryWrapper<Task>().in("t_id", teamIds).select("id"))
                    .stream()
                    .map(Task::getId).collect(Collectors.toList());
            if (!ObjectUtils.isEmpty(taskIds)){
                // 删除团队下的所有任务
                taskService.removeByIds(taskIds);
                // 删除任务记录表
                taskRecordService.remove(new QueryWrapper<TaskRecord>().in("t_id",taskIds));
            }
            // 删除团队用户中间表
            teamUserService.remove(new QueryWrapper<TeamUser>().in("t_id",teamIds));
            taskUserService.remove(new QueryWrapper<TaskUser>().in("t_id",taskIds));
        }catch (Exception e){
            log.error("删除团队出现错误");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error().message("删除失败");
        }
        return R.ok().message("删除成功");
    }

    @Override
    public R addTeam(Team team) {

        Integer uId = UserHolder.get();
        team.setInvitationCode(UuidUtil.getShortUuid());
        team.setUId(uId);
        team.setFileSizeUsed(null);
        team.setFileSizeCapacity(null);
        baseMapper.insert(team);
        return R.ok().message("创建成功");
    }

    @Override
    public R updateTeam(Team team) {
        team.setName(null);
        team.setFileSizeUsed(null);
        team.setFileSizeCapacity(null);
        Integer uId = UserHolder.get();
        baseMapper.update(team,new QueryWrapper<Team>().eq("u_id",uId));
        return R.ok().message("修改成功");
    }



    @Override
    @Transactional
    public R deleteTeam(String ids) {
        Integer uid = UserHolder.get();
        List<String> teamIds = Arrays.asList(ids.split(","));
        // 查出团队
        List<String> teams = baseMapper.selectBatchIds(teamIds).stream().map(Team::getName).collect(Collectors.toList());
        try{
            // 删除团队
            baseMapper.delete(new QueryWrapper<Team>().eq("u_id",uid).in("id",teamIds));
            // 删除任务下的记录
            // 查出任务id
            List<Integer> taskIds = taskService.list(new QueryWrapper<Task>().in("t_id", teamIds).select("id"))
                    .stream()
                    .map(Task::getId)
                    .collect(Collectors.toList());
            // 删除团队下的任务
            taskService.remove(new QueryWrapper<Task>().eq("u_id",uid).in("t_id",teamIds));
            if (!ObjectUtils.isEmpty(taskIds)){
                // 删除任务下的所有文件
                asyncService.removeByTaskIds(taskIds);
                taskRecordService.remove(new QueryWrapper<TaskRecord>().eq("u_id",uid).in("t_id",taskIds));
                // 删除任务用户中间表
                taskUserService.remove(new QueryWrapper<TaskUser>().in("t_id",taskIds));
            }
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error().message("删除失败,联系管理员");
        }
        return R.ok().message("删除成功");
    }

    @Resource
    private UserService userService;

    @Resource
    private UserRoleService userRoleService;

    @Override
    @Transactional
    public R addUser(User user, Integer teamId) {

        User u = userService.getOne(new QueryWrapper<User>().eq(!ObjectUtils.isEmpty(user.getEmail()),"email",user.getEmail()).eq("student_number", user.getStudentNumber()));

        // 校验: 学号和邮箱只能有一个为空
        if (ObjectUtils.isEmpty(user.getStudentNumber())){
            return R.error().message("学号不可为空");
        }
        try {
            // 用户不存在则创建用户
            if (ObjectUtils.isEmpty(u)){
                userService.save(user);
            }else {
                // 用户存在的话是否存在该团队中
                user = u;
                int count = teamUserService.count(new QueryWrapper<TeamUser>().eq("t_id", teamId).eq("u_id", user.getId()));
                if (count == 1){
                    return R.error().message("已存在团队中");
                }
            }
            // 加入团队用户中间表
            TeamUser teamUser = new TeamUser();
            teamUser.setTId(teamId);
            teamUser.setUId(user.getId());
            teamUserService.save(teamUser);
            UserRole userRole = new UserRole();
            userRole.setUId(user.getId());
            userRole.setRId(14);
            userRoleService.save(userRole);
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error().message("添加失败");
        }
        return R.ok().message("添加成功");
    }

    @Override
    public R deleteUsers(String ids,Integer teamId) {

        Integer uId = UserHolder.get();
        // 查出当前团队(校验是否是自己团队)
        Team team = baseMapper.selectOne(new QueryWrapper<Team>().eq("u_id", uId).eq("id", teamId));
        if (ObjectUtils.isEmpty(team)){
            return R.error().message("团队不存在");
        }
        List<String> userIds = Arrays.asList(ids.split(","));
        // 删除团队角色表数据
        teamUserService.remove(new QueryWrapper<TeamUser>().in("u_id",userIds));
        return R.ok().message("删除成功");
    }
}
